package com.isasc.demo.pooled.datasource;

import lombok.Setter;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.PooledObjectFactory;
import org.apache.commons.pool2.impl.DefaultPooledObject;
import org.apache.commons.pool2.impl.GenericObjectPool;

import java.sql.*;

/**
 * @author: ywy
 * @date: 2022-10-17
 * @desc:
 */
@Setter
public class ConnectionFactory implements PooledObjectFactory<MyConnection> {

    private GenericObjectPool<MyConnection> pool;

    @Override
    public PooledObject<MyConnection> makeObject() throws Exception {
        Class.forName("com.mysql.cj.jdbc.Driver");
        Connection connection = DriverManager.getConnection(
                "jdbc:mysql://localhost/foodie-shop-dev",
                "root",
                "rootroot"
        );
        MyConnection myConnection = new MyConnection();
        myConnection.setConnection(connection);
        myConnection.setPool(pool);
        return new DefaultPooledObject<MyConnection>(myConnection);
    }

    @Override
    public void destroyObject(PooledObject<MyConnection> p) throws Exception {
        p.getObject().close();
    }

    @Override
    public boolean validateObject(PooledObject<MyConnection> p) {
        try {
            PreparedStatement statement = p.getObject().prepareStatement("select 1");
            int i = statement.executeQuery().getInt(1);
            return i == 1;
        } catch (SQLException e) {
        }
        return false;
    }

    @Override
    public void activateObject(PooledObject<MyConnection> p) throws Exception {

    }

    @Override
    public void passivateObject(PooledObject<MyConnection> p) throws Exception {
        MyConnection myConnection = p.getObject();
        Statement statement = myConnection.getStatement();
        if(statement != null) {
            statement.close();
        }
    }
}